<template>
  <view class="file-preview-page">
    <!-- 导航栏 -->
    <u-navbar 
      title="文件预览" 
      :border="false"
      left-icon="arrow-left"
      @leftClick="goBack"
      :background="{ background: 'linear-gradient(135deg, #4a6bef, #7a5af8)' }"
      :titleStyle="{ color: '#ffffff', fontSize: '34rpx', fontWeight: 'bold' }"
      :leftIconColor="'#ffffff'"
    >
      <template #right>
        <view class="navbar-right" @tap="showActions = true">
          <u-icon name="more-dot-fill" size="20" color="#ffffff"></u-icon>
        </view>
      </template>
    </u-navbar>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <u-loading-icon mode="flower" size="36" color="#4a6bef"></u-loading-icon>
      <text class="loading-text">正在加载预览...</text>
    </view>
    
    <!-- 文件预览内容 -->
    <view v-else-if="fileInfo" class="preview-content">
      <!-- 图片预览 -->
      <view v-if="isImage" class="image-preview">
        <view class="image-container">
          <image 
            :src="currentImageUrl" 
            mode="aspectFit"
            class="preview-image"
            :style="{ transform: `scale(${zoomScale})` }"
            @tap="toggleFullscreen"
            @load="onImageLoad"
            @error="onImageError"
          />
        </view>
        
        <!-- 图片控制栏 -->
        <view class="image-controls">
          <view class="control-item" @tap="zoomOut">
            <u-icon name="minus" size="20" color="#ffffff"></u-icon>
          </view>
          <view class="zoom-info">
            <text>{{ Math.round(zoomScale * 100) }}%</text>
          </view>
          <view class="control-item" @tap="zoomIn">
            <u-icon name="plus" size="20" color="#ffffff"></u-icon>
          </view>
          <view class="control-item" @tap="resetZoom">
            <u-icon name="reload" size="20" color="#ffffff"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 文档预览 -->
      <view v-else class="document-preview">
        <!-- 预览图 -->
        <view v-if="fileInfo.previewUrl" class="document-thumbnail">
          <image 
            :src="fileInfo.previewUrl" 
            mode="aspectFit"
            class="thumbnail-image"
            @tap="viewFullPreview"
          />
          <view class="thumbnail-overlay">
            <u-icon name="eye" size="24" color="white"></u-icon>
            <text class="overlay-text">点击查看预览</text>
          </view>
        </view>
        
        <!-- 文档信息 -->
        <view class="document-info">
          <view class="info-header">
            <view class="file-icon">
              <u-icon :name="getFileIcon(fileInfo.fileType)" size="32" color="#4a6bef"></u-icon>
            </view>
            <view class="file-details">
              <text class="file-name">{{ fileInfo.originalName }}</text>
              <text class="file-meta">{{ formatFileSize(fileInfo.fileSize) }}</text>
            </view>
          </view>
          
          <view class="info-stats">
            <view v-if="fileInfo.pageCount" class="stat-item">
              <u-icon name="file-text" size="16" color="#909399"></u-icon>
              <text>{{ fileInfo.pageCount }} 页</text>
            </view>
            <view class="stat-item">
              <u-icon name="clock" size="16" color="#909399"></u-icon>
              <text>{{ formatDateTime(fileInfo.createdAt) }}</text>
            </view>
          </view>
        </view>
        
        <!-- 处理状态 -->
        <view v-if="!fileInfo.previewUrl" class="processing-status">
          <u-loading-icon mode="circle" size="24" color="#4a6bef"></u-loading-icon>
          <text class="status-text">正在生成预览图...</text>
          <button 
            class="reprocess-btn"
            @click="reprocessFile"
          >
            重新处理
          </button>
        </view>
      </view>
      
      <!-- 文件操作区域 -->
      <view class="file-actions">
        <view class="action-row">
          <button 
            class="action-btn primary"
            @click="printFile"
          >
            <u-icon name="printer" size="20" color="#ffffff" class="btn-icon"></u-icon>
            <text>打印文件</text>
          </button>
          
          <button 
            class="action-btn secondary"
            @click="downloadFile"
          >
            <u-icon name="download" size="20" color="#ffffff" class="btn-icon"></u-icon>
            <text>下载文件</text>
          </button>
        </view>
        
        <button 
          class="action-btn outline"
          @click="viewFileDetail"
        >
          <u-icon name="info-circle" size="20" color="#4a6bef" class="btn-icon"></u-icon>
          <text>文件详情</text>
        </button>
      </view>
    </view>
    
    <!-- 错误状态 -->
    <view v-else class="error-container">
      <u-empty 
        mode="data"
        icon="http://cdn.uviewui.com/uview/empty/data.png"
        text="文件加载失败"
        textColor="#909399"
      >
        <template #bottom>
          <button 
            class="error-btn"
            @click="loadFileDetail"
          >
            重新加载
          </button>
        </template>
      </u-empty>
    </view>
    
    <!-- 全屏预览 -->
    <u-overlay 
      :show="fullscreen" 
      @click="toggleFullscreen"
      :opacity="0.95"
      :z-index="9999"
    >
      <view class="fullscreen-container" @tap.stop>
        <image 
          :src="currentImageUrl" 
          mode="aspectFit"
          class="fullscreen-image"
        />
        <view class="fullscreen-close" @tap="toggleFullscreen">
          <u-icon name="close" size="24" color="white"></u-icon>
        </view>
      </view>
    </u-overlay>
    
    <!-- 操作菜单 -->
    <u-action-sheet 
      :show="showActions" 
      :actions="actionList"
      @close="showActions = false"
      @select="handleAction"
      title="文件操作"
      :round="10"
      :cancelText="'取消'"
    />
  </view>
</template>

<script>
export default {
  name: 'FilePreview',
  data() {
    return {
      fileId: null,
      fileInfo: null,
      loading: true,
      showActions: false,
      fullscreen: false,
      zoomScale: 1,
      currentImageUrl: '',
      actionList: [
        { name: '文件详情', value: 'detail', icon: 'info-circle', iconColor: '#4a6bef' },
        { name: '打印设置', value: 'print', icon: 'printer', iconColor: '#19be6b' },
        { name: '下载文件', value: 'download', icon: 'download', iconColor: '#4a6bef' },
        { name: '重新处理', value: 'reprocess', icon: 'reload', iconColor: '#909399' }
      ]
    }
  },
  
  computed: {
    // 是否为图片文件
    isImage() {
      return this.fileInfo && this.fileInfo.fileType && this.fileInfo.fileType.startsWith('image/')
    }
  },
  
  onLoad(options) {
    this.fileId = parseInt(options.id)
    if (this.fileId) {
      this.loadFileDetail()
    } else {
      this.loading = false
    }
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 加载文件详情
    async loadFileDetail() {
      this.loading = true
      
      try {
        const response = await this.$http.get(`/api/files/${this.fileId}`)
        
        if (response.data.success) {
          this.fileInfo = response.data.data
          
          // 设置当前图片URL
          if (this.isImage) {
            this.currentImageUrl = this.fileInfo.fileUrl
          }
        } else {
          throw new Error(response.data.message)
        }
      } catch (error) {
        console.error('加载文件详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        this.fileInfo = null
      } finally {
        this.loading = false
      }
    },
    
    // 重新处理文件
    async reprocessFile() {
      try {
        uni.showLoading({ 
          title: '处理中...',
          mask: true
        })
        
        const response = await this.$http.post(`/api/files/${this.fileId}/reprocess`)
        
        if (response.data.success) {
          uni.showToast({
            title: '处理成功',
            icon: 'success'
          })
          
          // 刷新文件信息
          this.loadFileDetail()
        } else {
          throw new Error(response.data.message || '处理失败')
        }
      } catch (error) {
        console.error('重新处理文件失败:', error)
        uni.showToast({
          title: error.message || '处理失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 打印文件
    printFile() {
      if (!this.fileInfo) return
      
      uni.navigateTo({
        url: `/pages/print/setup?fileId=${this.fileInfo.id}`
      })
    },
    
    // 下载文件
    async downloadFile() {
      if (!this.fileInfo) return
      
      try {
        uni.showLoading({ 
          title: '准备下载...',
          mask: true
        })
        
        const response = await this.$http.get(`/api/files/${this.fileId}/download`)
        
        if (response.data.success) {
          const downloadUrl = response.data.data.downloadUrl
          
          uni.downloadFile({
            url: downloadUrl,
            success: (res) => {
              if (res.statusCode === 200) {
                uni.hideLoading()
                uni.saveFile({
                  tempFilePath: res.tempFilePath,
                  success: () => {
                    uni.showToast({
                      title: '下载成功',
                      icon: 'success'
                    })
                  },
                  fail: (err) => {
                    console.error('保存文件失败:', err)
                    uni.showToast({
                      title: '保存失败',
                      icon: 'none'
                    })
                  }
                })
              }
            },
            fail: (err) => {
              console.error('下载文件失败:', err)
              uni.showToast({
                title: '下载失败',
                icon: 'none'
              })
            },
            complete: () => {
              uni.hideLoading()
            }
          })
        } else {
          throw new Error(response.data.message || '下载失败')
        }
      } catch (error) {
        console.error('下载文件失败:', error)
        uni.showToast({
          title: error.message || '下载失败',
          icon: 'none'
        })
        uni.hideLoading()
      }
    },
    
    // 查看文件详情
    viewFileDetail() {
      if (!this.fileInfo) return
      
      uni.navigateTo({
        url: `/pages/files/detail?id=${this.fileInfo.id}`
      })
    },
    
    // 查看完整预览
    viewFullPreview() {
      if (this.fileInfo.previewUrl) {
        uni.previewImage({
          urls: [this.fileInfo.previewUrl],
          current: this.fileInfo.previewUrl
        })
      }
    },
    
    // 切换全屏
    toggleFullscreen() {
      this.fullscreen = !this.fullscreen
    },
    
    // 放大
    zoomIn() {
      this.zoomScale = Math.min(this.zoomScale * 1.2, 3)
    },
    
    // 缩小
    zoomOut() {
      this.zoomScale = Math.max(this.zoomScale / 1.2, 0.5)
    },
    
    // 重置缩放
    resetZoom() {
      this.zoomScale = 1
    },
    
    // 图片加载完成
    onImageLoad() {
      console.log('图片加载成功')
    },
    
    // 图片加载错误
    onImageError() {
      console.error('图片加载失败')
      uni.showToast({
        title: '图片加载失败',
        icon: 'none'
      })
    },
    
    // 处理操作菜单
    handleAction(action) {
      this.showActions = false
      
      switch (action.value) {
        case 'detail':
          this.viewFileDetail()
          break
        case 'print':
          this.printFile()
          break
        case 'download':
          this.downloadFile()
          break
        case 'reprocess':
          this.reprocessFile()
          break
      }
    },
    
    // 获取文件图标
    getFileIcon(fileType) {
      if (!fileType) return 'file-text'
      
      if (fileType.includes('pdf')) return 'file-pdf'
      if (fileType.includes('word') || fileType.includes('document')) return 'file-word'
      if (fileType.includes('excel') || fileType.includes('sheet')) return 'file-excel'
      if (fileType.includes('powerpoint') || fileType.includes('presentation')) return 'file-ppt'
      if (fileType.includes('image')) return 'image'
      if (fileType.includes('text')) return 'file-text'
      
      return 'file'
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    
    // 格式化日期时间
    formatDateTime(dateString) {
      if (!dateString) return '未知时间'
      
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.file-preview-page {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.navbar-right {
  padding: 0 20rpx;
}

.loading-container, .error-container {
  padding: 120rpx 40rpx;
  text-align: center;
  
  .loading-text {
    display: block;
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #909399;
  }
}

.error-btn {
  margin-top: 30rpx;
  background: #4a6bef;
  color: white;
  font-size: 28rpx;
  padding: 16rpx 40rpx;
  border-radius: 40rpx;
  border: none;
  
  &:active {
    opacity: 0.9;
    transform: scale(0.98);
  }
}

.preview-content {
  height: calc(100vh - 88rpx);
  display: flex;
  flex-direction: column;
}

.image-preview {
  flex: 1;
  background: #000;
  position: relative;
  overflow: hidden;
  
  .image-container {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .preview-image {
      max-width: 100%;
      max-height: 100%;
      transition: transform 0.3s ease;
    }
  }
  
  .image-controls {
    position: absolute;
    bottom: 40rpx;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    background: rgba(0, 0, 0, 0.7);
    border-radius: 40rpx;
    padding: 16rpx 32rpx;
    z-index: 10;
    
    .control-item {
      padding: 16rpx;
      margin: 0 8rpx;
      
      &:active {
        opacity: 0.7;
      }
    }
    
    .zoom-info {
      margin: 0 20rpx;
      
      text {
        color: white;
        font-size: 28rpx;
      }
    }
  }
}

.document-preview {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
}

.document-thumbnail {
  position: relative;
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .thumbnail-image {
    width: 100%;
    height: 500rpx;
    object-fit: contain;
    background: #f8f9fa;
  }
  
  .thumbnail-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    .overlay-text {
      color: white;
      font-size: 28rpx;
      margin-top: 12rpx;
    }
  }
}

.document-info {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .info-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .file-icon {
      width: 80rpx;
      height: 80rpx;
      background: #f0f5ff;
      border-radius: 16rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
    }
    
    .file-details {
      flex: 1;
      
      .file-name {
        display: block;
        font-size: 32rpx;
        color: #303133;
        font-weight: 500;
        margin-bottom: 8rpx;
      }
      
      .file-meta {
        font-size: 26rpx;
        color: #909399;
      }
    }
  }
  
  .info-stats {
    display: flex;
    gap: 30rpx;
    
    .stat-item {
      display: flex;
      align-items: center;
      
      text {
        margin-left: 8rpx;
        font-size: 26rpx;
        color: #606266;
      }
    }
  }
}

.processing-status {
  background: white;
  border-radius: 16rpx;
  padding: 40rpx;
  text-align: center;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .status-text {
    display: block;
    margin: 20rpx 0;
    font-size: 28rpx;
    color: #606266;
  }
  
  .reprocess-btn {
    margin-top: 20rpx;
    background: #4a6bef;
    color: white;
    font-size: 28rpx;
    padding: 16rpx 40rpx;
    border-radius: 40rpx;
    border: none;
    
    &:active {
      opacity: 0.9;
      transform: scale(0.98);
    }
  }
}

.file-actions {
  padding: 20rpx;
  background: white;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .action-row {
    display: flex;
    gap: 20rpx;
    margin-bottom: 20rpx;
  }
  
  .action-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 88rpx;
    border-radius: 44rpx;
    font-size: 30rpx;
    border: none;
    
    .btn-icon {
      margin-right: 8rpx;
    }
    
    &.primary {
      flex: 1;
      background: #4a6bef;
      color: white;
      
      &:active {
        opacity: 0.9;
        transform: scale(0.98);
      }
    }
    
    &.secondary {
      flex: 1;
      background: #19be6b;
      color: white;
      
      &:active {
        opacity: 0.9;
        transform: scale(0.98);
      }
    }
    
    &.outline {
      width: 100%;
      background: white;
      color: #4a6bef;
      border: 1rpx solid #4a6bef;
      
      &:active {
        background: #f0f5ff;
        transform: scale(0.98);
      }
    }
  }
}

.fullscreen-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .fullscreen-image {
    max-width: 100%;
    max-height: 100%;
  }
  
  .fullscreen-close {
    position: absolute;
    top: 60rpx;
    right: 40rpx;
    width: 80rpx;
    height: 80rpx;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>